#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <sys/stat.h>
#include <cstring>
#include "log.hpp"
using namespace std;

Log logger;

#define FIFO_FILE "./myfifo"
#define MODE 0664

const string pathname = "/home";
const int proj_id = 0x666;
// 共享内存大小建议为4096的整数倍
// 4097,实际上操作系统给的大小是 4096 * 2;
const int size = 4096;

enum class Mistake
{
    FTOK_ERROR = 1,
    SHMGET_ERROR
};

key_t GetKey()
{
    key_t key = ftok(pathname.c_str(), proj_id);
    if (key < 0)
    {
        logger(Fatal, "ftok error\n");
        throw Mistake::FTOK_ERROR;
    }
    logger(Info, "ftok sucess key: %0x", key);
    return key;
}

int GetShareMemHelper(int flag)
{

    key_t k = GetKey();
    int shmid = shmget(k, size, flag);
    if (shmid < 0)
    {
        logger(Fatal, "shmid error\n");
        throw Mistake::SHMGET_ERROR;
    }
    logger(Info, "shmget sucess shmid: %d\n", shmid);
    return shmid;
}

int CreateShm()
{
    return GetShareMemHelper(IPC_CREAT | IPC_EXCL | 0666);
}

int GetShm()
{
    return GetShareMemHelper(IPC_CREAT);
}

 // 命名管道

enum
{
    FIFO_CREATE_ERR = 1,
    FIFO_DELETE_ERR = 2,
    FIFO_OPEN_ERROR = 3
};

class Init
{
public:
    Init()
    {

        // 创建信道
        int n = mkfifo(FIFO_FILE, MODE);
        if (n == -1)
        {
            perror("mkfifo");
            exit(FIFO_CREATE_ERR);
        }
    }
    ~Init()
    {
        int m = unlink(FIFO_FILE);
        if (m == -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }
};